<template>
  <div class="mod-prod-sku-table">
    <el-form-item>
      <el-table
        :data="modelValue"
        border
        style="width: 100%; margin-top: 20px"
        :span-method="objectSpanMethod"
      >
        <!-- 动态规格列 -->
        <el-table-column v-for="(title, index) in tableLeftTitles" :key="index" :label="title">
          <template #default="scope">
            {{ scope.row.properties.split(';')[index].split(':')[1] }}
          </template>
        </el-table-column>

        <!-- sku图片 -->
        <el-table-column v-if="tableLeftTitles.length" prop="pic" label="sku图片" width="180">
          <template #default="scope">
            <pic-upload v-model="scope.row.pic" />
          </template>
        </el-table-column>

        <!-- 商品名称 -->
        <el-table-column v-if="tableLeftTitles.length" prop="prodName" label="商品名称" width="250">
          <template #default="scope">
            <el-input v-model="scope.row.prodName" type="textarea" :disabled="!scope.row.status" />
          </template>
        </el-table-column>

        <!-- 价格、市场价、库存等 -->
        <el-table-column prop="price" label="销售价" width="160">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.price"
              controls-position="right"
              :precision="2"
              :max="1000000000"
              :min="0.01"
              :disabled="!scope.row.status"
            />
          </template>
        </el-table-column>
        <el-table-column prop="oriPrice" label="市场价" width="160">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.oriPrice"
              controls-position="right"
              :precision="2"
              :max="1000000000"
              :min="0.01"
              :disabled="!scope.row.status"
            />
          </template>
        </el-table-column>
        <el-table-column prop="stocks" label="库存" width="160">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.stocks"
              :min="0"
              controls-position="right"
              type="number"
              :disabled="!scope.row.status"
            />
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="商品重量(kg)" width="210">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.weight"
              :precision="2"
              :min="0"
              controls-position="right"
              :disabled="!scope.row.status"
            />
          </template>
        </el-table-column>
        <el-table-column prop="volume" label="商品体积(m³)" width="210">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.volume"
              :precision="2"
              :min="0"
              controls-position="right"
              :disabled="!scope.row.status"
            />
          </template>
        </el-table-column>

        <!-- 操作按钮：启用/禁用 -->
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="scope.row.status"
              type="text"
              @click="changeSkuStatus(`${scope.$index}`)"
            >
              禁用
            </el-button>
            <el-button v-else type="text" @click="changeSkuStatus(`${scope.$index}`)">
              启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
  </div>
</template>

<script setup>
  import { useProductStore } from '@/pinia/modules/product'
  import { getSpecList } from '@/plugin/Shop/api/sku'

  const props = defineProps({
    modelValue: {
      type: Array,
      default: () => [],
    },
    prodName: {
      type: String,
      default: '',
    },
  })
  const emit = defineEmits(['update:modelValue'])

  const prod = useProductStore()

  const skuTags = computed(() => prod.skuTags)

  // 表头：使用规格名
  const tableLeftTitles = computed(() => {
    // 确保与 row.properties 顺序一致（规格1, 规格2, 规格3...）
    return skuTags.value.map((tag) => tag.tagName)
  })

  let initing = false
  const dbSpecs = ref([])

  // 监听商品标题变化，同步给每个 SKU
  watch(
    () => props.prodName,
    () => {
      if (!initing) {
        skuAddProdName()
      }
    },
  )

  // 一旦 modelValue 改变，就对其排序；确保“相同规格1 的SKU”紧挨在一起
  watch(
    () => props.modelValue,
    (newVal) => {
      if (!newVal || !Array.isArray(newVal) || newVal.length < 2) return

      // 做一个深拷贝，以免直接修改 props.modelValue
      const sorted = [...newVal].sort((a, b) => sortCompare(a, b))
      // 如果排序后与原数组不同，则更新
      // 这里简单做一下“是否有变化”的判断
      let changed = false
      for (let i = 0; i < newVal.length; i++) {
        if (newVal[i] !== sorted[i]) {
          changed = true
          break
        }
      }
      if (changed) {
        emit('update:modelValue', sorted)
      }
    },
    { deep: true, immediate: true },
  )

  // 排序函数：按 splittedProps[0], splittedProps[1], splittedProps[2]... 一列列比较
  function sortCompare(skuA, skuB) {
    const splittedA = skuA.properties?.split?.(';')?.map((x) => x.split(':')[1]) || []
    const splittedB = skuB.properties?.split?.(';')?.map((x) => x.split(':')[1]) || []

    // 逐列 compare，先比较 specifications[0]，若相同再比较[1]，一直到末列
    const len = Math.max(splittedA.length, splittedB.length)
    for (let i = 0; i < len; i++) {
      const valA = splittedA[i] || ''
      const valB = splittedB[i] || ''
      const cmp = valA.localeCompare(valB, 'zh') // or 'en'，看需求
      if (cmp !== 0) {
        return cmp
      }
    }
    return 0
  }

  // onMounted：示例中仅用于获取数据库规格
  onMounted(async () => {
    const { data: dbData } = await getSpecList()
    dbSpecs.value = dbData
  })

  // ====================== 核心：分层合并逻辑 ======================
  function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    // 超出规格列范围(比如 "sku图片" / "价格" 等)，不做合并
    if (columnIndex >= tableLeftTitles.value.length) {
      return { rowspan: 1, colspan: 1 }
    }

    // 取出当前行的全部规格值，如 ["红","XL","短袖"] ...
    const splittedProps = row.properties?.split?.(';')?.map?.((item) => item.split(':')[1]) || []

    // groupKey = 「从第 0 列到当前列」的值 用 '|' 拼接
    const currentGroupKey = splittedProps.slice(0, columnIndex + 1).join('|')

    // 如果上一行相同 groupKey，则本行合并到上一行（rowspan=0, colspan=0）
    if (rowIndex > 0) {
      const prevRow = props.modelValue[rowIndex - 1]
      if (prevRow && prevRow.properties) {
        const prevSplitted =
          prevRow.properties?.split?.(';')?.map?.((item) => item.split(':')[1]) || []
        const prevGroupKey = prevSplitted.slice(0, columnIndex + 1).join('|')

        if (prevGroupKey === currentGroupKey) {
          return { rowspan: 0, colspan: 0 }
        }
      }
    }

    // 向后统计连续多少行与 currentGroupKey 相同，从而合并
    let rowspan = 1
    for (let i = rowIndex + 1; i < props.modelValue.length; i++) {
      const nextRow = props.modelValue[i]
      if (nextRow && nextRow.properties) {
        const nextSplitted =
          nextRow.properties?.split?.(';')?.map?.((item) => item.split(':')[1]) || []
        const nextGroupKey = nextSplitted.slice(0, columnIndex + 1).join('|')
        if (nextGroupKey === currentGroupKey) {
          rowspan++
        } else {
          break
        }
      }
    }
    return { rowspan, colspan: 1 }
  }
  // ====================== 分层合并结束 ======================

  // ================ 对外暴露 init 方法 ================
  function init() {
    initing = true
  }
  defineExpose({ init })

  // ================ 禁用&启用 SKU ================
  function changeSkuStatus(tagIndex) {
    props.modelValue[tagIndex].status = props.modelValue[tagIndex].status ? 0 : 1
  }

  // ================ 同步商品标题到每个 SKU ================
  function skuAddProdName() {
    if (initing) return
    const skuList = []
    for (let i = 0; i < props.modelValue.length; i++) {
      const sku = { ...props.modelValue[i] }
      if (!sku.properties) continue
      // 拼装规格名称
      sku.skuName = ''
      const propertiesArr = sku.properties.split(';')
      for (const propKey of propertiesArr) {
        const val = propKey.split(':')[1]
        sku.skuName += val + ' '
      }
      // 设置 prodName
      sku.prodName = props.prodName + ' ' + sku.skuName
      skuList.push(sku)
    }
    emit('update:modelValue', skuList)
  }
</script>

<style lang="scss" scoped>
  .mod-prod-sku-table {
    :deep(.pic-uploader-component .el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      .pic-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
      }
      .pic {
        width: 120px;
        height: 120px;
        display: block;
      }
    }
    :deep(.pic-uploader-component .el-upload:hover) {
      border-color: #409eff;
    }
  }
</style>
